const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");

const diskList = [];

function createDisk(diskNum = 1) {
    for (let i = 0; i < diskNum; i++) {
        let radius = Math.floor(Math.random() * 30 + 15),
            x = Math.random() * (canvas.width - radius * 2) + radius,
            y = Math.random() * (canvas.height - radius * 2) + radius,
            velocityX = Math.random() * 15 + 1,
            velocityY = Math.random() * 15 + 1,
            color = `rgba(${Math.random() * 255 + 1},${Math.random() * 255 +
                1},${Math.random() * 255 + 1},${Math.random()}`,
            strokeColor = `rgba(${Math.random() * 255 + 1},${Math.random() *
                255 +
                1},${Math.random() * 255 + 1},${Math.random()}`;

        diskList.push({
            x,
            y,
            color,
            strokeColor,
            radius,
            velocityX,
            velocityY
        });
    }
}

function drawDisk() {
    for (let i = 0, len = diskList.length; i < len; i++) {
        const { x, y, radius, color, strokeColor } = diskList[i];
        ctx.beginPath();
        ctx.save();
        ctx.arc(x, y, radius, 0, Math.PI * 2);
        ctx.fillStyle = color;
        ctx.strokeStyle = strokeColor;
        ctx.lineWidth = 3;
        ctx.fill();
        ctx.stroke();
        ctx.restore();
    }
}

function update() {
    for (let i = 0; i < diskList.length; i++) {
        const disk = diskList[i];
        const { x, y, radius, velocityX, velocityY } = disk;
        const { width: canvasWidth, height: canvasHeight } = canvas;

        if (
            x + velocityX + radius > canvasWidth ||
            x + velocityX - radius < 0
        ) {
            disk.velocityX = -disk.velocityX;
        }
        if (
            y + velocityY + radius > canvasHeight ||
            y + velocityY - radius < 0
        ) {
            disk.velocityY = -disk.velocityY;
        }

        disk.x += disk.velocityX;
        disk.y += disk.velocityY;
    }
}

function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    drawDisk();
    update();
    requestAnimationFrame(animate);
}

createDisk(10);

animate();
